package com.bmob.lover.ui.fragment.user

import android.graphics.Color
import android.view.View
import androidx.fragment.app.viewModels
import com.qmuiteam.qmui.skin.QMUISkinHelper
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction
import com.theone.common.ext.*
import com.theone.common.widget.datePicker.DateTimePicker
import com.bmob.lover.R
import com.bmob.lover.databinding.FragmentBindLoverBinding
import com.bmob.lover.ui.activity.IndexActivity
import com.bmob.lover.ui.fragment.base.BaseFragment
import com.bmob.lover.viewmodel.request.LoverBindActionViewModel
import com.bmob.lover.viewmodel.request.LoverBindRequestViewModel
import com.bmob.lover.viewmodel.request.UserRequestViewModel
import com.bmob.lover.viewmodel.state.BindLoverViewModel
import com.theone.mvvm.core.app.ext.addFailTipsObserve
import com.theone.mvvm.ext.qmui.*
import java.util.*

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 * @author The one
 * @date 2021-06-08 10:23
 * @describe 绑定另一半
 * @email 625805189@qq.com
 * @remark 流程：用户输入另一个半的objectId(用户信息界面可查）
 *              1.先查询用户是否存在。
 *              2.再查询该用户是否绑定。
 *              3.创建绑定。
 */
class BindLoverFragment : BaseFragment<BindLoverViewModel, FragmentBindLoverBinding>(),
    DateTimePicker.ResultHandler {

    private val mUserRequest: UserRequestViewModel by viewModels()
    private val mLoverBindRequest: LoverBindRequestViewModel by viewModels()
    private val mLoverBindActionRequest: LoverBindActionViewModel by viewModels()

    override fun initView(root: View) {
        setTitleWitchBackBtn(R.string.bind_lover)
    }

    override fun createObserver() {
        addLoadingObserve(mUserRequest, mLoverBindActionRequest)
        addFailTipsObserve(mUserRequest, mLoverBindActionRequest)
        mUserRequest.getResponseLiveData().observe(this) {
            hideLoadingDialog()
            // TODO 2 查询该用户是否绑定
            getBindLover(it.objectId)
        }
        mLoverBindRequest.getResponseLiveData().observe(this) {
            if (it.isEmpty()) {
                // TODO 3 开始绑定
                mLoverBindActionRequest.create(
                    getViewModel().loverDate.get(),
                    getViewModel().loverId.get()
                )
            } else {
                val bind = it[0]
                if(null != bind.getBindLover(mAppVm.getUserInfoLiveData().value)){
                    mAppVm.setLoverBind(bind)
                    context?.showMsgDialog(
                        title = null,
                        message = "恭喜，绑定成功，即将开启二人世界。",
                        leftAction = null,
                        listener = QMUIDialogAction.ActionListener { dialog, index ->
                            dialog.dismiss()
                            startActivity(IndexActivity::class.java,true)
                        })
                }else{
                    showFailTipsDialog("TA已经心有所属了~")
                }
            }
        }
        mLoverBindActionRequest.getObjectSuccessLiveDate().observe(this) {
            getBindLover(mAppVm.getUserInfoLiveData().value?.objectId!!)
        }
    }

    /**
     * 查询用户绑定
     * @param id String
     */
    private fun getBindLover(id:String){
        mLoverBindRequest.mUserId = id
        mLoverBindRequest.requestServer()
    }

    /**
     * 获取用户信息
     * @param id String?
     * @param loadingMsg String
     */
    private fun getUserInfo(id: String?, loadingMsg: String) {
        with(mUserRequest) {
            userId = id
            loadMsg = loadingMsg
            requestServer()
        }
    }

    override fun getBindingClick() = ProxyClick()

    inner class ProxyClick  {

        fun bind() {
            val loverId = getViewModel().loverId.get()
            when {
                loverId.isEmpty() -> showFailTipsDialog("请填写对方ID")
                loverId == mAppVm.getUserInfoLiveData().value?.objectId -> showFailTipsDialog("和自己怎么搞")
                else -> {
                    // TODO 查询该用户是否存在
                    getUserInfo(loverId, "正在查找该用户")
                }
            }
        }

        fun loveDate() {
            mDatePicker.show(getViewModel().loverDate.get().formatDate())
        }
    }

    override fun handle(date: Date?) {
        date?.let {
            getViewModel().loverDate.set(it.formatString())
        }
    }

    private val mDatePicker: DateTimePicker by lazy {
        DateTimePicker(
            mActivity,
            this,
            getYearDate(1990),
            Date(),
            DateTimePicker.Builder(mActivity).apply {
                setOk("确定")
                setOk("确定")
                setCancel("取消")
                setCancelTextColor(Color.RED)
                setOkTextColor(getColor(mActivity, R.color.qmui_config_color_blue))
                setTitleTextColor(getColor(mActivity, R.color.qmui_config_color_gray_3))
                setKeepLastSelected(true)
                setSelectedTextColor(
                    QMUISkinHelper.getSkinColor(
                        getContentView(),
                        R.attr.app_skin_primary_color
                    )
                )
                setShowType(DateTimePicker.ShowType.DAY)
            })
    }


}